import CryptoJS from "crypto-js";

// 加密
const encrypt = function (str, privateKey) {
  let key = CryptoJS.enc.Utf8.parse(privateKey);
  let srcs = CryptoJS.enc.Utf8.parse(str);
  let encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });

  // 将加密后的数据转换成 Base64
  let base64Cipher = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
  // 处理 Android 某些低版的BUG
  let resultCipher = base64Cipher.replace(/\+/g, "-").replace(/\//g, "_");
  return resultCipher;
};

// 解密
const decrypt = function (str, privateKey) {
  var key = CryptoJS.enc.Utf8.parse(privateKey);
  var decrypt = CryptoJS.AES.decrypt(str, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
};

export default {
  encrypt,
  decrypt,
};
